var parentId;
var nodeText;
var resource_sm;
var sroleStore;
var resourceTree;
Ext.onReady(function() {
	function reloadResource(sid){
		sroleStore.on('beforeload' , function(){
			//设置 点击树时 刷新列表所用的 参数
	  		sroleStore.baseParams = {id:sid};
		});
		
		sroleStore.reload();
	}
	function fnCheckNodeByName(name){
		var conn = Ext.lib.Ajax.getConnectionObject().conn;
		conn.open("POST", 'resourceManAction!checkNodeByName.action',false);
		conn.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		conn.send("node.groupName="+name);
		var responseTextVale = Ext.util.JSON.decode(conn.responseText);
		return responseTextVale.nodeId;
	}
	
	function fnTreeReload(val, nodeText){
		var node = resourceTree.getNodeById(parentId);
		if(val==""){
			nodeId = fnCheckNodeByName(nodeText);
			if(node.isLeaf())
				node.leaf=false;
			node.appendChild([{id:nodeId,text:nodeText,leaf:true}]);
		}else
			node.setText(nodeText);
	}
	
	//点击新增资源按钮
	function fnAddPrivilege(){
		return addRoleAction = new Ext.Action({
					text : '新增资源',
					iconCls : 'add',
					handler : function() {
						if(parentId==null||parentId=="undefined"||parentId==""){
							Ext.Msg.alert("警告","请先选择结点!");
						}else
							resourceWin().show();
					}
		});
	}
	// 点击编辑资源按钮
	function fnEditPrivilege(){
		return editRoleAction = new Ext.Action({
			text : '编辑资源',
			iconCls : 'option',
			handler : function() {
				if(parentId==null||parentId=="undefined"||parentId==""){
							Ext.Msg.alert("警告","请先选择资源!");
							return;
				}else{
					var recordLength = resourceGrid.getSelectionModel().getSelections().length;
					if (recordLength < 1) {
						Ext.Msg.alert('警告', '请选择需要修改的资源');
						return;
					}
					if (recordLength > 1) {
						Ext.Msg.alert('警告', '只能选择一个资源进行修改');
						return;
					}
					
					Ext.Ajax.request({
						url : "resourceManAction!retrieveRes.action?res.id="
								+ resourceGrid.getSelectionModel().getSelections()[0].data.id,
						method : "post",
						success : function(response, options) {
							var responseTextVale = Ext.util.JSON.decode(response.responseText);
							document.getElementById("res_id").value = responseTextVale.res.id;
							document.getElementById("res_displayName").value = responseTextVale.res.displayName;
							document.getElementById("res_displayName").readOnly = true;
							document.getElementById("res_disabled").value = responseTextVale.res.disabled==null?"":responseTextVale.res.disabled;
							document.getElementById("res_value").value = responseTextVale.res.value;
							document.getElementById("res_type").value = responseTextVale.res.type;
						}
					});
				}
			
				resourceWin().show();
			}
		})
	}
	//点击删除资源按钮
	function fnDelPrivilege(){
		return delRoleAction = new Ext.Action({
					text : '删除资源',
					tooltip : '删除',
					iconCls : 'remove',
					handler : function() {
						var recordLength = resourceGrid.getSelectionModel()
							.getSelections().length;
						if (recordLength > 0) {
							Ext.MessageBox.confirm('确认删除', '你确认要删除' + recordLength
											+ '条数据吗?', function(btn) {
										if (btn == "yes") {
											var deleteResId = [];
											var rs = resourceGrid.getSelectionModel()
													.getSelections();
											for (var i = 0; i < recordLength; i++) {
												var resId = rs[i].data.id;
												deleteResId.push(resId);
												sroleStore.remove(sroleStore.getById(resId));
											}
											Ext.Ajax.request({
												url : 'resourceManAction!deleteResByResId.action?resIds='
														+ Ext.encode(deleteResId)+"&node.groupCode="+parentId,
												success:function(){
													sroleStore.reload();
												}
											});
										}
									});
						} else {
							Ext.Msg.alert('提示', '请选择要删除的数据项!');
						}
					}
				});
	}
	//点击新增结点按钮
	function fnaddNode(){
		return addNodeAction = new Ext.Action({
					text : '新增结点',
					iconCls : 'add',
					handler : function() {
						if(parentId==null||parentId=="undefined"||parentId==""){
							Ext.Msg.alert("警告","请选择结点!");
						}else{
							moduleWin().show();
						}
					}
		});
	}
	//删除结点
	function fnDelNode(){
		return delNodeAction = new Ext.Action({
					text : '删除结点',
					iconCls : 'remove',
					handler : function() {
						if(parentId==null||parentId=="undefined"||parentId==""){
							Ext.Msg.alert("警告","请选择要删除的结点!");
						}else{
							Ext.MessageBox.confirm('确认删除', '你确认要删除此结点吗?', function(btn) {
									if (btn == "yes") {
										Ext.Ajax.request({
											url : 'resourceManAction!deleteNode.action?node.groupCode='+parentId,
									success : function(response, options) {
										var responseTextVale = Ext.util.JSON.decode(response.responseText);
										var msg = responseTextVale.msg;
										if(msg!=null&&msg!="undefined"&&msg!=""){
											Ext.Msg.alert("警告", "该结点下有"+msg+"个子结点,请删除子结点后再删除此结点!");
										}else{
											resourceTree.getNodeById(parentId).remove();
											parentId = "";
										}
									}
										});
									}
								});
						}
					}
		});
	}
	//编辑结点
	function fnEditNode(){
		return editNodeAction = new Ext.Action({
					text : '编辑结点',
					iconCls : 'option',
					handler : function() {
						if(parentId==null||parentId=="undefined"||parentId==""){
							Ext.Msg.alert("警告","请选择结点!");
							return;
						}
	
						Ext.Ajax.request({
							url : "resourceManAction!retrieveNode.action?node.groupCode="+parentId,
							method : "post",
							success : function(response, options) {
								var responseTextVale = Ext.util.JSON.decode(response.responseText);
								document.getElementById("node_groupCode").value = parentId;
								document.getElementById("node_groupName").value = responseTextVale.node.groupName;
								document.getElementById("node_groupMemo").value = responseTextVale.node.groupMemo==null?"":responseTextVale.node.groupMemo;
								document.getElementById("node_groupSupcode").value = responseTextVale.node.groupSupcode;
							}
						});
			
						moduleWin().show();
						Ext.getCmp('node_groupName').selectText(0,100);
					}
		});
	}
	var fnModuleFormPanel=function() {
					var addNodePanel = new Ext.form.FormPanel({
								frame : true,
	//							title : '结点信息',
								width:445,
								collapsible : true,
								id : 'moduleFormPanel',
								bodyStyle : 'padding:5px 5px 0',
								items : [{
									layout : 'column',
									items : [{
												columnWidth : .0005,
												layout : 'form',
												items : [{
															xtype : 'hidden',
															name : 'node.groupCode',
															id : 'node_groupCode'
														}]
											},{
												columnWidth : .0005,
												layout : 'form',
												items : [{
															xtype : 'hidden',
															name : 'node.groupSupcode',
															id : 'node_groupSupcode'
														}]
											}, {
												columnWidth : .999,
												layout : 'form',
												items : [{
															xtype : 'textfield',
															fieldLabel : '结点名',
															name : 'node.groupName',
															id : 'node_groupName',
															anchor : '95%',
															allowBlank : false,
															blankText : '结点名称不能为空',
															emptyText : '请输入结点名称'
														}, {
															xtype : 'textarea',
															fieldLabel : '结点描述',
															name : 'node.groupMemo',
															id : 'node_groupMemo',
															anchor : '95%',
															decimalPrecision : 3,
															allowNegative : false,
															minValue : 0,
															maxValue : 1,
															allowBlank : true
														}]
											}
											]
											
								}]
							});
					return addNodePanel;
				}
	var moduleWin=function(){
		return new Ext.Window({
			id : 'moduleWin',
			modal : true,
			width : 450,
			height : 180,
			closeAction : 'close',
			plain : true,
			title : '结点',
			items : [fnModuleFormPanel()],
			buttons : [{
				text : '保存',
				handler : function() {
					var panel = Ext.getCmp('moduleFormPanel');
					var frm = panel.getForm();
					if(frm.isValid()){
						var nodeId = panel.form.findField("node_groupCode");
						var urlAdd = "";
						if (nodeId.getValue() == "") {
							var res = fnCheckNodeByName(panel.form.findField("node_groupName").getValue());
//							alert(res);
							if(res!=null&&res!="undefined"&&res!=""){
								Ext.Msg.alert('提示', '该结点名称已经存在,请重新输入!');
								return;
							}else{
								panel.form.findField("node_groupSupcode").setValue(parentId);
								urlAdd = 'resourceManAction!addNode.action';// 新增资源的action
							}
						} else {
							urlAdd = 'resourceManAction!updateNode.action';// 更新资源的action
						}
//						alert('当前选择的结点的父结点是:'+panel.form.findField("node_groupSupcode").getValue());
						
						frm.submit({
							url : urlAdd,
							success : function(from, action) {
								Ext.Msg.alert('提示', '操作资源失败!');
							},
							failure : function(form, action) {
								sroleStore.reload();
								//刷新树
								fnTreeReload(nodeId.getValue(), panel.form.findField("node_groupName").getValue());
								Ext.getCmp('moduleWin').close();
								
							},
							waitMsg : '正在保存数据，稍后...'
						});
						
					}else{
						Ext.Msg.alert("警告", "请输入完整信息.");
					}
				}
			}, {
				text : '取消',
				handler : function() {
					var rolewin = Ext.getCmp('moduleWin');
					rolewin.close();
				}
			}]
		});
	}
	var fnResourceFormPanel=function() {
					var resourcePanel = new Ext.form.FormPanel({
								frame : true,
	//							title : '结点信息',
								width:445,
								collapsible : true,
								id : 'resourceFormPanel',
								bodyStyle : 'padding:5px 5px 0',
								items : [{
									layout : 'column',
									items : [
											{//parentId
												columnWidth : 1,
												layout : 'form',
												items : [{
															xtype : 'textfield',
															name : 'nodeText',
															id : 'nodeText',
															fieldLabel : '结点名称',
															value : nodeText,
															readOnly : true
														}]
											},
											{
												columnWidth : .5,
												layout : 'form',
												items : [{
															xtype : 'hidden',
															name : 'res.id',
															id : 'res_id'
														}]
											},{
												columnWidth : .5,
												layout : 'form',
												items : [{
															xtype : 'hidden',
															name : 'node.groupCode',
															id : 'node_groupCode',
															value : parentId
														}]
											}, {
												columnWidth : 1,
												layout : 'form',
												items : [{
															xtype : 'textfield',
															fieldLabel : '资源名',
															name : 'res.displayName',
															id : 'res_displayName',
															anchor : '95%',
															allowBlank : false,
															blankText : '资源名称不能为空',
															emptyText : '请输入资源名称'
														}, {
															xtype : 'textfield',
															fieldLabel : '资源值',
															name : 'res.value',
															id : 'res_value',
															anchor : '95%',
															decimalPrecision : 3,
															allowNegative : false,
															minValue : 0,
															maxValue : 1,
															allowBlank : false,
															blankText : '资源值不能为空',
															emptyText : '请输入资源值'
														}]},{
												columnWidth : 1,
												layout : 'form',
												items : [{
													xtype : 'combo',
													fieldLabel : '是否启用',
													editable : false,
													width : 97,
													emptyText : '',
													mode : 'local',
													anchor : '90%',
													hiddenName : 'res.disabled',
													id : 'res_disabled',
													allowBlank : false,
													triggerAction : 'all',
													valueField : "returnValue",
													displayField : "displayText",
													store : new Ext.data.SimpleStore(
													{
														fields : [
																"returnValue",
																"displayText"],
														data : [[0, '启用'],
																[1, '冻结']]
													})
												},{
													xtype : 'combo',
													fieldLabel : '资源类型',
													editable : false,
													width : 97,
													emptyText : '',
													mode : 'local',
													anchor : '90%',
													hiddenName : 'res.type',
													id : 'res_type',
													allowBlank : false,
													triggerAction : 'all',
													valueField : "returnValue",
													displayField : "displayText",
													store : new Ext.data.SimpleStore(
													{
														fields : [
																"returnValue",
																"displayText"],
														data : [[0, 'URL'],
																[1, '按钮'],
																[9, '其他']]
													})
											}]
											}
											]
											
								}]
							});
					return resourcePanel;
				}
	var resourceWin=function(){
		return new Ext.Window({
			id : 'resourceWin',
			modal : true,
			width : 450,
			height : 220,
			closeAction : 'close',
			plain : true,
			title : '资源',
			items : [fnResourceFormPanel()],
			buttons : [{
				text : '保存',
				handler : function() {
					var panel = Ext.getCmp('resourceFormPanel');
					var frm = panel.getForm();
					if(frm.isValid()){
						var resId = panel.form.findField("res_id");
						var urlAdd = "";
						if (resId.getValue() == "") {
							urlAdd = 'resourceManAction!addRes.action';// 新增资源的action
						} else {
							urlAdd = 'resourceManAction!updateRes.action';// 更新资源的action
						}
						frm.submit({
							url : urlAdd,
							success : function(from, action) {
								Ext.Msg.alert('提示', '操作结点失败!');
							},
							failure : function(response) {
								reloadResource(parentId);
								Ext.getCmp('resourceWin').close();
								
							},
							waitMsg : '正在保存数据，稍后...'
						});
					}else{
						Ext.Msg.alert("警告", "请输入完整信息.");
					}
				}
			}, {
				text : '取消',
				handler : function() {
					var rolewin = Ext.getCmp('resourceWin');
					rolewin.close();
				}
			}]
		});
	}
	
	resource_sm = new Ext.grid.CheckboxSelectionModel();
		sroleStore = new Ext.data.Store({
				url : 'roleManagementAction!getResourceById.action',
				method: 'post',
				reader : new Ext.data.JsonReader({
							totalProperty : 'result.totalCount',
							root : 'result.result',
							id : 'id'
						}, [{
									name : 'id',
									mapping : 'id'
								}, {
									name : 'displayName',
									mapping : 'displayName'
								}])
		});
	function treeReload(tree){
		Ext.Ajax.request({
				url : 'roleManagementAction!initializeTree.action',
				method : "post",
				success : function(response, options) {
					var responseTextVale = Ext.util.JSON.decode(response.responseText);
					tree.getRootNode().setText(responseTextVale.root.groupName);
					tree.getRootNode().id = responseTextVale.root.groupCode;
					for(var i =0;i<Ext.util.JSON.decode(responseTextVale.treeListJson.length);i++){
						tree.getRootNode().appendChild(Ext.util.JSON.decode(responseTextVale.treeListJson[i]));
					}
					tree.render();
//					tree.expandAll();
				}
			});
	}
	//树开始
		function resTreePanel() {
			var root = new Ext.tree.AsyncTreeNode({
				expanded : true
			});
	
			var treeloader = new Ext.tree.TreeLoader({
				dataUrl : 'roleManagementAction!empty.action'
			});
			
			resourceTree = new Ext.tree.TreePanel({
				region : 'west',
				id : 'resourceTree',
				animCollapse : false,
				autoScroll : true,
				autoDestroy : true,
				tbar : [fnaddNode(), '-', fnEditNode(), '-', fnDelNode()],
				title : '功能模块',
				root : root,
				achor : '50%',
				height : document.body.clientHeight-40,
				deferHeight : false,
				loader : treeloader,
				rootVisible : true,
				frame : true
			});
		
			treeReload(resourceTree);
			
			resourceTree.on("click", function(node, event) {
				var id = node.id;
				if(parentId==id){//如果已经是当前节点,就不刷新
					return;
				}else{//否则刷新
					parentId=id;
					nodeText = node.text;
					reloadResource(id);
				}
			});
			return resourceTree;
		}
		//树结束
		function fnresourceGrid() {
			var resourceCM = new Ext.grid.ColumnModel([
					new Ext.grid.RowNumberer(),
					resource_sm,
					{
						header : " 资源名 ",
						dataIndex : "displayName",
						width : 280
					}]);
			resourceGrid = new Ext.grid.GridPanel({
						title : '可操作资源',
						height : document.body.clientHeight-60,
						region : 'center',
						tbar : [fnAddPrivilege(), '-', fnEditPrivilege(), '-', fnDelPrivilege()],
						achor : '40%',
						cm : resourceCM,
						sm : resource_sm,
						store : sroleStore,
						autoExpandColumn : false,
						frame : true
			});
	
			return resourceGrid;
		}
	var mainPanel = new Ext.form.FormPanel({
							frame : true,
							title : '角色信息',
							
							height : document.body.clientHeight,
							id : 'addRolePanelForm',
							bodyStyle : 'padding:5px 5px 0',
							items : [{
								layout : 'column',
								items : [{
											columnWidth : .5,
											layout : 'form',
											items : [resTreePanel()]
										}, {
											columnWidth : .5,
											layout : 'form',
											items : [fnresourceGrid()]
										}]
							}]
						});
	mainPanel.render(Ext.getBody());
});